package com.jqq.map_;

import java.util.Comparator;
import java.util.TreeMap;

/**
 * @author 姬倩倩
 * @version 1.0
 */
@SuppressWarnings({"all"})
public class TreeMap_ {
    public static void main(String[] args) {
        //使用默认的构造器创建TreeMap，默认是无序的
//        TreeMap treeMap = new TreeMap();
        TreeMap treeMap = new TreeMap(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                //按传入的key(String)的大小进行排序
//                return ((String)o1).compareTo((String)o2);
                //按传入的key(String)的长度大小进行排序
                return ((String)o1).length() - ((String)o2).length();
            }
        });
        treeMap.put("jack", "杰克");
        treeMap.put("tom", "汤姆");
        treeMap.put("smith", "斯密斯");
        treeMap.put("jqq", "jqq");

        System.out.println("treeMap=" + treeMap);
        //treeMap={tom=jqq, jack=杰克, smith=斯密斯}
        /*
        1.构造器，把传入的实现了Comparator接口的匿名内部类传给TreeMap的comparator属性
        public TreeMap(Comparator<? super K> comparator) {
            this.comparator = comparator;
        }
        2.调用put方法
        2.1 第一次添加，把k-v 封装到Entry对象，放入root
        if (t == null) {
            compare(key, key); // type (and possibly null) check

            root = new Entry<>(key, value, null);
            size = 1;
            modCount++;
            return null;
        }
        2.2 之后添加时
        Comparator<? super K> cpr = comparator;
        if (cpr != null) {
            do {//遍历所有的key
                parent = t;
                cmp = cpr.compare(key, t.key);//动态绑定到匿名内部类的compare方法
                if (cmp < 0)
                    t = t.left;
                else if (cmp > 0)
                    t = t.right;
                else
                    return t.setValue(value);//替换value
            } while (t != null);
        }

         */
    }
}
